<template>
  <div class="doc-list-page">
    <div class="doc-main">
      <!-- 左侧分类筛选 -->
      <aside class="doc-sidebar">
        <div class="sidebar-menu">
          <div class="sidebar-title" title="全部分类">全部分类</div>
          <el-tree
            ref="treeRef"
            class="custom-tree"
            style="max-width: 600px"
            :highlight-current="true"
            :data="menuData"
            :props="DEFAULT_TREE_PROPS"
            node-key="id"
            :default-expanded-keys="[...expandedKeys]"
            :current-node-key="selectedId"

            accordion
            @node-click="handleNodeClick"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse"
          >
            <template #default="{ node, data }">
              <span :class="{ 'my-highlight': currentKeys.includes(data.id) }">
                {{ data.name }}
              </span>
            </template>
          </el-tree>
          <!--          <el-menu :unique-opened="true"
                             :class="'menu-left'"
                             :collapse-transition="false"
                             @select="handleSelectMenu"
                             @close="handleClose"
                             ref="menuRef"

                    >
                      <LeftSubMenu :menuData="menuData"></LeftSubMenu>
                    </el-menu>-->
        </div>
        <div class="sidebar-recommend">
          <div class="sidebar-recommend-title">推荐文档</div>
          <div>
            <HotList class="hot-list" :list="recommendDocs"></HotList>
          </div>
        </div>
      </aside>

      <!-- 右侧文档列表和筛选 -->
      <section class="doc-content">
        <div class="doc-outer">
                      <div class="doc-classify-name">
              <span>{{selectedNodeName}}</span>
              <span>({{ selectedId ? sumDocs + '  篇文档' : '4.8万+  篇文档' }})</span>
            </div>
          <div class="doc-filter-bar">
            <div class="filter-row">
              <span class="filter-label">页数</span>
              <span
                v-for="option in FILTER_OPTIONS.pageCount"
                :key="option.value"
                class="filter-item"
                :class="{ active: activeFilters.pageCount === option.value }"
                @click="setActiveFilter('pageCount', option.value)"
              >{{ option.label }}</span>
            </div>
            <div class="filter-row">
              <span class="filter-label">时间</span>
              <span
                v-for="option in FILTER_OPTIONS.timeRange"
                :key="option.value"
                class="filter-item"
                :class="{ active: activeFilters.timeRange === option.value }"
                @click="setActiveFilter('timeRange', option.value)"
              >{{ option.label }}</span>
            </div>
            <div class="filter-row">
              <span class="filter-label">类型</span>
              <span
                v-for="option in FILTER_OPTIONS.docType"
                :key="option.value"
                class="filter-item"
                :class="{ active: activeFilters.docType === option.value }"
                @click="setActiveFilter('docType', option.value)"
              >{{ option.label }}</span>
            </div>
            <div class="filter-row filter-search">
              <span class="filter-label">搜索</span>
              <input
                class="filter-search-input"
                v-model="searchKeyword"
                placeholder="输入文档标题"
                @keyup.enter="handleSearch"
              />
              <button class="filter-search-btn" @click="handleSearch">搜索</button>
              <button class="filter-reset-btn" @click="handleReset">重置</button>
            </div>
          </div>

          <div class="doc-list-table">
            <div class="doc-table-bar">
            <span
              v-for="tab in TAB_OPTIONS"
              :key="tab.value"
              class="table-tab"
              :class="{ active: activeTab === tab.value }"
              @click="setActiveTab(tab.value)"
            >{{ tab.label }}</span>
            </div>
            <div v-for="doc in docList" :key="doc.id" class="doc-list-row" @click="docClick(doc.id)">
              <div class="doc-list-thumb">
                <img :src="doc.coverUrl" alt="thumb" />
                <img
                  v-if="getTypeIcon(doc.type)"
                  class="doc-type-icon"
                  :src="getTypeIcon(doc.type)"
                  :alt="getTypeText(doc.type)"
                />
              </div>
              <div class="doc-list-info">
                <div class="doc-list-title">{{ doc.name }}</div>
                <div class="doc-list-meta">
                  <div>
                    <span><svg-icon name="time" class="doc-list-meta-icon"></svg-icon></span>
                    <span>{{ doc.createTime?.slice(0,10) }}</span>
                  </div>
                  <div>
                    <span><svg-icon name="fileSize" class="doc-list-meta-icon"></svg-icon></span>
                    <span>{{ doc.size }}</span>
                  </div>
                  <div>
                    <span><svg-icon name="view" class="doc-list-meta-icon"></svg-icon></span>
                    <span>{{ doc.views }}次浏览</span>
                  </div>
                  <div>
                    <span><svg-icon name="download" class="doc-list-meta-icon"></svg-icon></span>
                    <span>{{ doc.downloads }}下载</span>
                  </div>
                  <div>
                    <span><svg-icon name="price" class="doc-list-meta-icon"></svg-icon></span>
                    <span>{{ doc.favorites }}点赞</span>
                  </div>
                  <div>
                    <span><svg-icon name="price" class="doc-list-meta-icon"></svg-icon></span>
                    <span>{{ doc.coin }}知币</span>
                  </div>
                </div>
              </div>
              <div class="doc-list-action">
                <!--              <span class="doc-list-vip" v-if="doc.vip">VIP</span>
                              <span class="doc-list-pdf">PDF</span>-->
              </div>
            </div>
          </div>
          <div class="page">
            <el-pagination background layout="prev, pager, next" :total="totalPage"
                           :hide-on-single-page="true"
                           :default-page-size = "pageSize"
                           :page-size = "pageSize"
                           @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
// ===== 导入部分 =====
import { onMounted, ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import HotList from '@/components/home/HotList.vue'
import * as DropdownApi from '@/api/dropdown'
import * as DocListApi from '@/api/doclist'

// 导入图标资源
import pdfIcon from '@/assets/img/file/PDF.png'
import docIcon from '@/assets/img/file/WORD.png'
import pptxIcon from '@/assets/img/file/PPT.png'
import zipIcon from '@/assets/img/file/ZIP.png'
import router from '@/router'
import SvgIcon from '@/components/SvgIcon/index.vue'

// ===== 类型定义 =====
interface ElTreeNode {
  data: DropdownApi.PDFDropDownTreeNode;
  childNodes: ElTreeNode[];
  expanded: boolean;
  level: number;
  key: string;
  isLeaf: boolean;
}

type FilterType = 'pageCount' | 'timeRange' | 'docType' | 'sortType'

// ===== 常量配置 =====
const DEFAULT_PAGE_SIZE = 10
const DEFAULT_SELECTED_NODE_NAME = '全部文档'

const DEFAULT_FILTERS = {
  pageCount: 'all',
  timeRange: 'all',
  docType: 'all',
  sortType: 'latest'
}

const FILTER_OPTIONS = {
  pageCount: [
    { label: '全部', value: 'all' },
    { label: '1-9页', value: '1-9' },
    { label: '10-19页', value: '10-19' },
    { label: '20页以上', value: '20+' }
  ],
  timeRange: [
    { label: '全部', value: 'all' },
    { label: '近一周', value: 'week' },
    { label: '近一月', value: 'month' },
    { label: '近三月', value: 'quarter' }
  ],
  docType: [
    { label: '全部', value: 'all' },
    { label: 'VIP专享', value: 'vip' },
    { label: '免费', value: 'free' }
  ]
} as const

const TAB_OPTIONS = [
  { label: '最新上传', value: 'latest_upload' },
  { label: '热门下载', value: 'hot_download' },
  { label: '浏览优先', value: 'view_priority' },
  { label: '收藏优先', value: 'collect_priority' }
] as const

const DEFAULT_TREE_PROPS = {
  children: 'children',
  label: 'name',
} as const

// ===== 基础状态 =====
const route = useRoute()
const props = defineProps<{ id?: string }>()

// DOM引用
const treeRef = ref()

// 基础数据状态
const menuData = ref<DropdownApi.PDFDropDownTreeNode[]>([])
const recommendDocs = ref([])
const docList = ref<DocData[]>([])
const sumDocs = ref<number>(0);

// 分页状态
const totalPage = ref<number>(0)
const pageSize = ref<number>(DEFAULT_PAGE_SIZE)
const pageNumber = ref<number>(0)

// 选中状态
const selectedId = ref(props.id)
const currentKeys = ref<string[]>([])
const expandedKeys = ref<string[]>([])
const routerParentKeys = ref<string[]>([])

// 筛选状态
const activeFilters = ref({ ...DEFAULT_FILTERS })
const searchKeyword = ref('')
const activeTab = ref('latest_upload')

// UI状态
const loading = ref(false)
const error = ref<string>('')

// ===== 计算属性 =====
const selectedNodeName = computed(() => {
  if (!selectedId.value || !menuData.value.length) return DEFAULT_SELECTED_NODE_NAME
  return findNodeNameById(menuData.value, selectedId.value) || DEFAULT_SELECTED_NODE_NAME
})


// ===== 工具函数 =====
/**
 * 在树形数据中根据ID查找节点名称
 */
function findNodeNameById(data: DropdownApi.PDFDropDownTreeNode[], nodeId: string): string {
  for (const node of data) {
    if (node.id === nodeId) {
      return node.name
    }
    if (node.children) {
      const found = findNodeNameById(node.children, nodeId)
      if (found) return found
    }
  }
  return ''
}

/**
 * 获取节点的所有父级节点ID
 */
function getVisibleParentKeys(
  data: DropdownApi.PDFDropDownTreeNode[],
  key: string,
  parentKeys: string[] = []
): string[] | null {
  for (const node of data) {
    if (node.id === key) {
      return parentKeys
    }
    if (node.children) {
      const found = getVisibleParentKeys(node.children, key, [...parentKeys, node.id])
      if (found) return found
    }
  }
  return null
}

/**
 * 递归折叠所有子节点
 */
function collapseAllChildren(node: ElTreeNode): void {
  if (node.childNodes && node.childNodes.length > 0) {
    node.childNodes.forEach((childNode: ElTreeNode) => {
      childNode.expanded = false

      const index = expandedKeys.value.indexOf(childNode.key)
      if (index > -1) {
        expandedKeys.value.splice(index, 1)
      }
      collapseAllChildren(childNode)
    })
  }
}

// ===== 筛选相关函数 =====
/**
 * 获取传给后端的筛选参数
 */
function getFilterParams() {
  return {
    pageCount: activeFilters.value.pageCount,
    timeRange: activeFilters.value.timeRange,
    docType: activeFilters.value.docType,
    sortType: activeFilters.value.sortType,
    keyword: searchKeyword.value,
    tab: activeTab.value,
    classifyId: selectedId.value,
    pageSize: pageSize.value,
    pageNumber: pageNumber.value,
  }
}

/**
 * 设置激活的筛选项
 */
function setActiveFilter(filterType: FilterType, value: string): void {
  activeFilters.value[filterType] = value
  fetchDocList()
}

/**
 * 搜索处理函数
 */
function handleSearch(): void {
  fetchDocList()
}

/**
 * 重置筛选条件
 */
function handleReset(): void {
  activeFilters.value = { ...DEFAULT_FILTERS }
  searchKeyword.value = ''
  fetchDocList()
}

/**
 * 设置激活的标签页
 */
function setActiveTab(tabValue: string): void {
  activeTab.value = tabValue
  fetchDocList()
}

// ===== 树操作相关函数 =====
/**
 * 节点展开处理
 */
function handleNodeExpand(data: DropdownApi.PDFDropDownTreeNode): void {
  // 关闭其他展开的节点（手风琴效果）
  const allNodes = treeRef.value?.store?._getAllNodes() || []
  allNodes.forEach((child: ElTreeNode) => {
    if (expandedKeys.value.includes(child.data.id)) {
      const collSpanChilds = child.childNodes
      collSpanChilds.forEach((collSpanChild: ElTreeNode) => {
        if (collSpanChild.data.id !== data.id) {
          collSpanChild.expanded = false
        }
      })
    }
  })

  expandedKeys.value = [...(routerParentKeys.value || [])]
  const allParentKeys = getVisibleParentKeys(menuData.value, data.id) || []
  if (!expandedKeys.value.includes(data.id)) {
    expandedKeys.value = [...allParentKeys, data.id]
  }
}

/**
 * 节点折叠处理
 */
function handleNodeCollapse(data: DropdownApi.PDFDropDownTreeNode, node: ElTreeNode): void {
  collapseAllChildren(node)
  if (node.level === 1) {
    expandedKeys.value = []
    routerParentKeys.value = []
  } else {
    expandedKeys.value = expandedKeys.value.filter(id => id !== data.id)
  }
}

/**
 * 节点点击处理
 */
function handleNodeClick(data: DropdownApi.PDFDropDownTreeNode, node: ElTreeNode): void {
  if (node.isLeaf) {
    const allParentKeys = getVisibleParentKeys(menuData.value, data.id) || []
    currentKeys.value = [...allParentKeys, data.id]
  } else {
    currentKeys.value = [...expandedKeys.value]
  }

  // 更新选中的节点ID
  selectedId.value = data.id

  // 更新URL参数，保留Vue Router状态避免警告和闪动
  const newUrl = `${route.path}?id=${data.id}&t=${Date.now()}`
  window.history.replaceState(window.history.state, '', newUrl)

  // 重新获取文档列表
  fetchDocList()
}

// ===== 数据获取相关 =====
/**
 * 获取文档列表数据
 */
async function fetchDocList(): Promise<void> {
  try {
    loading.value = true
    error.value = ''

    const filterParams = getFilterParams()
    const data = await DocListApi.getDocList(filterParams)

    docList.value = data.data
    totalPage.value = data.total
    sumDocs.value = data.total
  } catch (err) {
    error.value = '获取文档列表失败'
    console.error('fetchDocList error:', err)
  } finally {
    loading.value = false
  }
}

/**
 * 获取下拉菜单数据
 */
async function fetchDropdownData(): Promise<void> {
  try {
    menuData.value = await DropdownApi.getDropDownList()
  } catch (err) {
    error.value = '获取菜单数据失败'
    console.error('fetchDropdownData error:', err)
  }
}

/**
 * 初始化组件数据和状态
 */
async function initializeComponent(): Promise<void> {
  try {
    // 获取菜单数据
    await fetchDropdownData()

    // 初始化树状态
    const parentKeys = getVisibleParentKeys(menuData.value, selectedId.value || '') || []
    routerParentKeys.value = parentKeys
    currentKeys.value = [...parentKeys, selectedId.value || '']
    expandedKeys.value = [...parentKeys, selectedId.value || ''].filter(Boolean)

    // 初始化文档列表
    await fetchDocList()
  } catch (err) {
    error.value = '初始化组件失败'
    console.error('initializeComponent error:', err)
  }
}

function handleCurrentChange(val: number){
  pageNumber.value = val;
  fetchDocList()
}

// ===== 文件类型相关函数 =====
/**
 * 根据类型获取图标路径
 */
function getTypeIcon(type: number | undefined): string {
  const iconMap: Record<number, string> = {
    0: pdfIcon,
    1: docIcon,
    2: pptxIcon,
    3: zipIcon

  }
  return iconMap[type as number] || ''
}

/**
 * 根据类型获取文本描述
 */
function getTypeText(type: number | undefined): string {
  const textMap: Record<number, string> = {
    0: 'PDF文档',
    1: 'Word文档',
    2: 'PowerPoint文档'
  }
  return textMap[type ?? 0] || 'PDF文档'
}

// 跳转到文档详情页的方法
const docClick = async (id: string | number) => {
  console.log('docClick triggered with id:', id, 'type:', typeof id)

  // 更严格的ID验证
  if (!id || id === '' || id === '0' || id === 0) {
    console.warn('Invalid document ID:', id)
    return
  }

  const docId = id.toString().trim()
  if (!docId) {
    console.warn('Document ID is empty after conversion:', id)
    return
  }

  try {
    await router.push({
      name: 'doc_view',
      params: { id: docId }
    })
    console.log('Navigation successful to doc_view with id:', docId)
  } catch (error) {
    console.error('Navigation failed:', error)
    // ElMessage.error('页面跳转失败，请重试')
  }
}

// ===== 生命周期 =====
onMounted(() => {
  initializeComponent()
})
</script>

<style scoped>
/* 热门列表组件样式覆盖 */
.hot-list {
  --item-img-width: 90px;
  --item-img-height: 90px;
  --item-info-text-width: 140px;
}

/* 菜单 css begin*/
.custom-tree :deep(.el-tree-node) {
  padding: 6px 0;
  transition: all 0.3s ease;
}

.custom-tree :deep(.el-tree-node__expand-icon) {
  font-size: 15px;
}

.custom-tree{
  padding: 0 8px 5px 8px;
  border-right: none;
  background: none;
  font-size: 16px;
  max-height: 560px;
  overflow-y: auto;
  overflow-x: hidden;
}
/* 菜单 css end*/

.doc-list-page {
  background: #f5f5f5;
  min-height: calc(100vh - 75px);
  margin-top: 75px;
}

.doc-main {
  display: flex;
  max-width: 1280px;
  margin: 20px auto;
  gap: 10px;
}

.doc-sidebar {
  width: 270px;
  border-radius: 4px;
  box-sizing: border-box;
  flex-shrink: 0;
  user-select: none;
}

.sidebar-title {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  display: flex;
  align-content: center;
  justify-content: center;
  align-items: center;
  height: 60px;
  background-color: #3580e6;
  color: #fff;
}

.sidebar-menu{
  max-height: 620px;
  height: 620px;
  margin-bottom: 10px;
  background: #fff;
  overflow: hidden;
}

.sidebar-recommend {
  background: #fff;
  padding: 20px;
}

.sidebar-recommend-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 10px;
}

.doc-content {
  flex: 1;
  border-radius: 4px;
  min-width: 0;
  display: flex;
  gap: 10px;
  flex-direction: column;
}

.doc-classify-name {
  font-size: 18px;
  height: 56px;
  font-weight: bold;
  padding: 15px;
  background: #fff;
  position: relative;
  box-sizing: border-box;
  z-index: 1;
  display: flex;
  align-items: center;
  gap: 5px;
}

.doc-classify-name::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 15px;
  right: 15px;
  height: 1px;
  background-color: #eee;
}

.doc-classify-name span{
  padding: 0;
}

.doc-classify-name span:nth-child(2){
  font-size: 13px;
  color: #999;
}

.doc-filter-bar {
  padding: 15px;
  background: #fff;
  font-size: 16px;
  position: relative;
  z-index: 0;
}

.doc-filter-bar .filter-row:last-of-type{
  margin-bottom: 0;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.filter-label {
  font-size: 15px;
  color: #999;
  margin-right: 8px;
  height: 25px;
  line-height: 25px;
}

.filter-item {
  font-size: 15px;
  color: #666;
  padding: 0 10px;
  height: 25px;
  line-height: 25px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.filter-item.active, .filter-item:hover {
  background: #3580e6;
  color: #f0f6ff;
}

.filter-search {
  margin-top: 8px;
}

.filter-search-input {
  width: 300px;
  height: 32px;
  border: 1px solid #e0e0e0;
  border-radius: 16px 0 0 16px;
  padding: 0 12px;
  font-size: 14px;
  outline: none;
}

.filter-search-btn, .filter-reset-btn {
  height: 32px;
  border: none;
  background: #1890ff;
  color: #fff;
  border-radius: 0 16px 16px 0;
  padding: 0 16px;
  cursor: pointer;
  font-size: 14px;
  margin-left: 4px;
}

.filter-reset-btn {
  background: #e0e0e0;
  color: #333;
}

.doc-table-bar {
  display: flex;
  gap: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.table-tab {
  font-size: 15px;
  color: #666;
  cursor: pointer;
  padding: 2px 10px;
  border-radius: 2px;
  transition: all 0.2s;
}

.table-tab.active, .table-tab:hover {
  background: #f0f6ff;
  color: #1890ff;
  font-weight: bold;
}

.doc-list-table {
  background: #fff;
  padding: 15px;
  margin-top: 15px;
}

.doc-list-row {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 0;
  gap: 16px;
}

.doc-list-row:hover{
  cursor: pointer;
}

.doc-list-row:hover .doc-list-title{
  text-decoration: underline;
}

.doc-list-row:hover .doc-list-title{
    color: #3580e6;
}

.doc-list-row:hover .doc-list-thumb img:nth-child(1) {
  transform: scale(1.2);
}

.doc-list-thumb {
  width: 120px;
  height: 140px;
  background: #f8f9fa;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.doc-list-thumb img {
  width: 100%;

  object-fit: cover;
  display: block;
  transition: transform 0.5s ease;
}

.doc-type-icon {
  position: absolute !important;
  bottom: 4px !important;
  right: 4px !important;
  width: 55px !important;
  height: 32px !important;
  object-fit: contain !important;
  border-radius: 3px !important;
  padding: 2px !important;
}

.doc-list-info {
  display: flex;
  flex-direction: column;
  gap: 70px;
  flex: 1;
  min-width: 0;
}

.doc-list-title {
  font-size: 16px;
  color: #333;
  font-weight: bold;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.doc-list-meta {
  font-size: 13px;
  color: #999;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.doc-list-meta div {
  display: flex;
  gap: 5px;
}

.doc-list-meta-icon{
  width: 20px;
  height: 20px;
  fill: #999;
}

.doc-list-action {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 6px;
  min-width: 50px;
}

.doc-list-vip {
  background: #ffe58f;
  color: #bfa21a;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  font-weight: bold;
}

.doc-list-pdf {
  background: #e0e0e0;
  color: #333;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  font-weight: bold;
}

.page {
  background: #fff;
  padding-bottom: 15px;
  display: flex;
  justify-content: center;
}

.my-highlight {
  color: #1890ff;
  font-weight: bold;
  border-radius: 4px;
}

.item-info-img {
  width: var(--item-img-width, 160px);
  height: var(--item-img-height, 90px);
}
</style>
